<html>
<body>
Type an SQL SELECT query in the following box:
<form method="GET" action="query.php">
<textarea name="input" rows="10" cols="80" warp="physical"/>
</textarea>
<input type="submit" value="Submit"/>
</form>

<?php
	// Open the connection and check it
	$db_connection = mysql_connect("localhost", "cs143", "");
	if (!db_connection) {
		$errmsg = mysql_error($db_connection);
		print "Connection failed: $errmsg <br/>";
		exit(1);
	}

	// Select CS143 database
	mysql_select_db("CS143", $db_connection);

	// Handle query from GET
	if ($_GET["input"]) {
		// Get query
		$query = $_GET["input"];
		$result = mysql_query($query, $db_connection);
		
		// Check if query is valid
		if (!$result) {
			$errmsg = mysql_error($db_connection);
			print "<b>MySQL Error:</b> $errmsg<br/>";
			mysql_close($db_connection);
			exit(1);
		}

		// Print out results in a table
		print "<b>Results from MySQL:</b><br/><br/>";
		print "<table cellpadding='5' border='1'>";
		
		// Get the fields from query (@ to suppress error messages)
		$i = 0;
		while ($field = @mysql_field_name($result, $i)) {
			print "<td><b>$field</b></td>";
			$i++;
		}
		
		// Fetch each entry and print
		while ($row = mysql_fetch_row($result)) {
			print "<tr align='center'>";
			// Print out each entry in each row, NULL are represented as N/A
			foreach ($row as $entry) {
				if (is_null($entry)) 
					print "<td>N/A</td>";
				else
					print "<td>$entry</td>";
			}
			print "</tr>";
		}
		print "</table>";
	}

	// Close the connection
	mysql_close($db_connection);
?>

</body>
</html>
